import time
import sys
import json

from 爬取评论 import getReplyResp, getSubReplyResp


def getAllComment(aid):
    # 获取评论
    cursor = 0
    is_end = False
    reply_list = []
    while 1:
        resp = getReplyResp(aid, cursor)
        resp_dict = resp.json()
        if resp_dict.get('code') != 0:
            print(f'获取评论失败，检查响应！\n{aid, cursor}\n{resp_dict}')
            input('#####按回车重新获取本次请求')
            continue
        data = resp_dict.get('data')
        cursor = data.get('cursor').get('next')
        is_end = data.get('cursor').get('is_end')
        replies = data.get('replies')
        for reply in replies:
            reply_list.append(reply)
            rcount = reply.get('rcount')
            if rcount > 0:
                rpid = reply.get('rpid')
                for pn in range(1, int(rcount / 10) + 2):
                    while 1:
                        subReplyResp = getSubReplyResp(aid, rpid, pn)
                        subReplyResp_dict = subReplyResp.json()
                        if subReplyResp_dict.get('code') != 0:
                            print(f'获取子评论失败，检查响应！\n{aid, rpid, pn}\n{resp_dict}')
                            input('#####按回车重新获取本次请求')
                            continue
                        break
                    time.sleep(1) # 防止爬取太快-412风控
                    subReplies = subReplyResp_dict.get('data').get('replies')
                    reply_list.extend(subReplies)  # 列表内添加子评论的响应
        time.sleep(1)  # 防止爬取太快-412风控
        if is_end:
            break

    with open(f'./av{aid}评论响应.json', 'w', encoding='utf-8') as f:
        f.write(json.dumps(reply_list, indent=4))
    sys.stdout.flush()
    for i in reply_list:
        print(i.get('content',{}).get('message',''))
if __name__ == '__main__':
    getAllComment(1750499714)
